//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package dao

import (
	"context"

	"atomgit.com/openlinksaas/api-server/dao/db_ns"
	"atomgit.com/openlinksaas/proto-gen-go.git/feedback_api"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type FeedBackInfoDbItem struct {
	FeedBackId string `bson:"_id"`
	Content    string `bson:"content"`
	UserId     string `bson:"userId"`
	TimeStamp  int64  `bson:"timeStamp"`
}

func (item *FeedBackInfoDbItem) ToFeedBackInfo() *feedback_api.FeedBackInfo {
	return &feedback_api.FeedBackInfo{
		FeedBackId: item.FeedBackId,
		Content:    item.Content,
		UserId:     item.UserId,
		TimeStamp:  item.TimeStamp,
	}
}

type _FeedBackDao struct {
	mc *mongo.Collection
}

func newFeedBackDao(db *mongo.Database) (*_FeedBackDao, error) {
	mc := db.Collection(db_ns.DB_NS_GLOBAL + "feedback")
	_, err := mc.Indexes().CreateMany(context.Background(), []mongo.IndexModel{
		{
			Keys: bson.D{{"userId", 1}, {"timeStamp", -1}},
		},
		{
			Keys: bson.D{{"timeStamp", -1}},
		},
	})
	if err != nil {
		return nil, err
	}
	return &_FeedBackDao{mc: mc}, nil
}

func (db *_FeedBackDao) Insert(ctx context.Context, dbItem *FeedBackInfoDbItem) error {
	_, err := db.mc.InsertOne(ctx, dbItem)
	return err
}

func (db *_FeedBackDao) Exist(ctx context.Context, feedBackId string) (bool, error) {
	count, err := db.mc.CountDocuments(ctx, bson.M{"_id": feedBackId})
	return count > 0, err
}

func (db *_FeedBackDao) Remove(ctx context.Context, feedBackId, userId string) error {
	_, err := db.mc.DeleteOne(ctx, bson.M{"_id": feedBackId, "userId": userId})
	return err
}

func (db *_FeedBackDao) ForceRemove(ctx context.Context, feedBackId string) error {
	_, err := db.mc.DeleteOne(ctx, bson.M{"_id": feedBackId})
	return err
}

func (db *_FeedBackDao) Count(ctx context.Context, filterByUserId bool, userId string) (uint32, error) {
	query := bson.M{}
	if filterByUserId {
		query["userId"] = userId
	}
	count, err := db.mc.CountDocuments(ctx, query)
	return uint32(count), err
}

func (db *_FeedBackDao) List(ctx context.Context, filterByUserId bool, userId string, offset, limit int64) ([]*FeedBackInfoDbItem, error) {
	query := bson.M{}
	if filterByUserId {
		query["userId"] = userId
	}
	cursor, err := db.mc.Find(ctx, query, options.Find().SetSkip(offset).SetLimit(limit).SetSort(bson.M{"timeStamp": -1}))
	if err != nil {
		return nil, err
	}
	retList := []*FeedBackInfoDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}
